package com.base_data_handler.utils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

public class HttpRequest {
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式
     *            fileName文件名。saveDir保存路径
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param,int type,String fileName,String saveDir) {
        String result = "";
  
      
		try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
//            System.out.println(realUrl.openConnection().getContentType()+"字符编码"+realUrl.openConnection().getContentEncoding());
            realUrl.openConnection().setConnectTimeout(30*60*60*1000);
            realUrl.openConnection().setReadTimeout(30*60*60*1000);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
            connection.setRequestProperty("Host", "d1.weather.com.cn");
            connection.setRequestProperty("Pragma", "no-cache");
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setRequestProperty("Referer", "http://www.weather.com.cn/live/");
            connection.setRequestProperty("Accept-Encoding", " gzip, deflate, sdch");
            connection.setRequestProperty("Cookie", " vjuids=24e1a4cdb.15c2eaed31f.0.efd8ca5ee076e; f_city=%E5%85%B0%E5%B7%9E%7C101160101%7C; BIGipServerd1src_pool=1874396221.20480.0000; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1495431828; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1495432309; vjlast=1495431828.1495431828.30");
            connection.setRequestProperty("ETag", "5927bd74-77fe");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            
            //如果是字符串
            if(type==1){
                BufferedReader in = null;
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                
            	while ((line = in.readLine()) != null) {
                    result += line;
                }
            }else{
            	System.out.println("数据大小"+connection.getContentLength());
            	//图片
            	File dir=new File(saveDir);
            	if(!dir.exists())dir.mkdirs();
            	
            	//用输出流写到SDcard上面
            	 File file = new File(dir+"/"+fileName);
//            	 System.out.println(file.getAbsolutePath());
            	 file.createNewFile();
				 FileOutputStream fos=new FileOutputStream(file);
				  InputStream in=connection.getInputStream() ;
                //创建byte数组  用于1KB写一次 
                byte[] buffer=new byte[1024*1];  
                int count = 0;  
                while((count = in.read(buffer))>0){  
                    fos.write(buffer,0,count);
                }  

              //关闭就可以了  
                fos.flush();  
                fos.close();  
                in.close();
                result="ok";
            }
            
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            result="发送GET请求出现异常！";
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
//                if (in != null) {
//                    in.close();
//                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
        	
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
            conn.setRequestProperty("Host", "d1.weather.com.cn");
            conn.setRequestProperty("Pragma", "no-cache");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Referer", "http://www.weather.com.cn/live/");
            conn.setRequestProperty("Accept-Encoding", " gzip, deflate, sdch");
            conn.setRequestProperty("Cookie", " vjuids=24e1a4cdb.15c2eaed31f.0.efd8ca5ee076e; f_city=%E5%85%B0%E5%B7%9E%7C101160101%7C; BIGipServerd1src_pool=1874396221.20480.0000; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1495431828; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1495432309; vjlast=1495431828.1495431828.30");
            
//            GET /newwebgis/fo/json/r3h_list.json?callback=getData&_=1495433351557 HTTP/1.1
//            		Host: d1.weather.com.cn
//            		Connection: keep-alive
//            		Pragma: no-cache
//            		Cache-Control: no-cache
//            		User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
//            		Accept: */*
//            		Referer: http://www.weather.com.cn/live/
//            		Accept-Encoding: gzip, deflate, sdch
//            		Accept-Language: zh-CN,zh;q=0.8
//            		Cookie: vjuids=24e1a4cdb.15c2eaed31f.0.efd8ca5ee076e; f_city=%E5%85%B0%E5%B7%9E%7C101160101%7C; BIGipServerd1src_pool=1874396221.20480.0000; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1495431828; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1495432309; vjlast=1495431828.1495431828.30


            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
    
    public static void main(String[] args) {
        //发送 GET 请求
//    	http://d1.weather.com.cn/newwebgis/fo/json/r3h_list.json?callback=getData&_=1495433087005
        String s=HttpRequest.hContent("http://d1.weather.com.cn/newwebgis/sk/json/r_list.jsonn", "callback=getData&_="+System.currentTimeMillis(),1,null,null);
        System.out.println(s);
        
        //发送 POST 请求
//        String sr=HttpRequest.sendPost("http://d1.weather.com.cn/newwebgis/fo/json/r3h_list.json", "callback=getData&_="+System.currentTimeMillis());
//        System.out.println(sr);
    }
    
    
    public static String hContent(String url, String param,int type,String fileName,String saveDir){
    	 String result="";
		try {
			  String urlNameString = url + "?" + param;
                URL realUrl = new URL(urlNameString);
			    // 打开和URL之间的连接
                HttpURLConnection  conn = (HttpURLConnection) realUrl.openConnection();
			    // 设置通用的请求属性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent",
	                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
	            conn.setRequestProperty("Host", "d1.weather.com.cn");
	            conn.setRequestProperty("Pragma", "no-cache");
	            conn.setRequestProperty("Cache-Control", "no-cache");
	            conn.setRequestProperty("Referer", "http://www.weather.com.cn/live/");
	            conn.setRequestProperty("Accept-Encoding", " gzip, deflate, sdch");
	            conn.setRequestProperty("Cookie", " vjuids=24e1a4cdb.15c2eaed31f.0.efd8ca5ee076e; f_city=%E5%85%B0%E5%B7%9E%7C101160101%7C; BIGipServerd1src_pool=1874396221.20480.0000; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1495431828; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1495432309; vjlast=1495431828.1495431828.30");
			    //System.out.println(realUrl.openConnection().getContentEncoding());
			    GZIPInputStream in = new GZIPInputStream(conn.getInputStream());
			    InputStreamReader r = new InputStreamReader(in,"utf-8");
			    BufferedReader  bf = new BufferedReader(r);
	            String line;
	           
	            while ((line = bf.readLine()) != null) {
	                 result += line;
	            }
//	            System.out.println(result); 
		} catch (Exception e) {
			e.printStackTrace();
		}
			return result;  
    } 
    
    public static String gizpContent(String url, String param,int type,String fileName,String saveDir){
   	 String result="";
		try {
			  String urlNameString = url + "?" + param;
               URL realUrl = new URL(urlNameString);
			    // 打开和URL之间的连接
               HttpURLConnection  conn = (HttpURLConnection) realUrl.openConnection();
			    // 设置通用的请求属性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent",
	                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
	            conn.setRequestProperty("Host", "d1.weather.com.cn");
	            conn.setRequestProperty("Pragma", "no-cache");
	            conn.setRequestProperty("Cache-Control", "no-cache");
	            conn.setRequestProperty("Referer", "http://www.weather.com.cn/live/");
	            conn.setRequestProperty("Accept-Encoding", " gzip, deflate, sdch");
	            conn.setRequestProperty("Cookie", " vjuids=24e1a4cdb.15c2eaed31f.0.efd8ca5ee076e; f_city=%E5%85%B0%E5%B7%9E%7C101160101%7C; BIGipServerd1src_pool=1874396221.20480.0000; Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b=1495431828; Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b=1495432309; vjlast=1495431828.1495431828.30");
			    //System.out.println(realUrl.openConnection().getContentEncoding());
			    GZIPInputStream in = new GZIPInputStream(conn.getInputStream());
			    InputStreamReader r = new InputStreamReader(in,"utf-8");
			    BufferedReader  bf = new BufferedReader(r);
	            String line;
	           
	            while ((line = bf.readLine()) != null) {
	                 result += line;
	            }
//	            System.out.println(result); 
		} catch (Exception e) {
			e.printStackTrace();
		}
			return result;  
   } 
}